//
//  AppDelegate.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/14.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "AppDelegate.h"
#import <ViewDeck/ViewDeck.h>
#import "MBBaseTabbarController.h"
#import "MBLoginController.h"//登录
#import "MBUserCenterController.h"
#import "TXLiveBase.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import "MBUserCenterModel.h"
#import <AlipaySDK/AlipaySDK.h>
@interface AppDelegate ()<RCIMUserInfoDataSource,RCIMGroupInfoDataSource>
@property (nonatomic) IIViewDeckController *viewDeckController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    MBLoginController* mainVC = [[MBLoginController alloc]init];
//    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:mainVC];
    
    // 自动登录
    
    //沙盒ducument目录
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //完整的文件路径
    NSString *path = [docPath stringByAppendingPathComponent:@"userModel.archive"];
    
    MBUserModel *userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (userModel != nil) {
        [MBUserModel sharedMBUserModel].isLoginFlag = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
    }
    
    MBBaseTabbarController * mainVC = [[MBBaseTabbarController alloc]init];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    MBUserCenterController *userCenterVC = [[MBUserCenterController alloc] init];
    UINavigationController *sideNavigationController = [[UINavigationController alloc] initWithRootViewController:userCenterVC];
    
    IIViewDeckController *viewDeckController = [[IIViewDeckController alloc] initWithCenterViewController:mainVC leftViewController:sideNavigationController rightViewController:[[MBBaseController alloc]init]];
//    viewDeckController.rightEdgeGestureRecognizer.enabled = NO;
    self.window.rootViewController= viewDeckController;
    [self.window makeKeyAndVisible];
    [TXUGCBase setLicenceURL:TencentLicenseURL key:TencentKey];
    [self configUMShare];
    [self configKeyboardManager];
    
    // 融云初始化
    [[RCIM sharedRCIM] initWithAppKey:kRongCloudKey];
    
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    
    
    
    [self configTXChat];
    
    if ([MBUserModel sharedMBUserModel].phone != nil) {
        [MBHttpRequset requestWithUrl:kTradeid_login_login setParams:@{@"phone":[MBUserModel sharedMBUserModel].phone} isShowProgressView:NO success:^(id  _Nonnull AJson) {
            [[RCIM sharedRCIM] connectWithToken:AJson[@"token"]  success:^(NSString *userId) {
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                
            } error:^(RCConnectErrorCode status) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:[NSString stringWithFormat:@"登陆的错误码为:%ld", (long)status]];
                });
            } tokenIncorrect:^{
                //token过期或者不正确。
                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
//                [MBProgressHUD showError:@"token错误"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"token错误"];
//                    IIViewDeckController *viewDeckController = (IIViewDeckController *)self.window.rootViewController;
//                    UINavigationController *sideNavigationController = (UINavigationController *)viewDeckController.leftViewController;
//                    [self needLoginVC:sideNavigationController.viewControllers[0]];
                });
            }];
            
            
            MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
            [MBUserModel sharedMBUserModel].isLoginFlag = YES;
            
            [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
            [self tencentChatLoginWith:userModel];
        } failure:^(id  _Nonnull AJson) {
            
        }];
    }
    
    

    
//    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:kUserPhone];
//    if(phone != nil)
//    {
//        [MBHttpRequset requestWithUrl:kTradeid_login_login setParams:@{@"phone":phone} isShowProgressView:NO success:^(id  _Nonnull AJson) {
//            [[RCIM sharedRCIM] connectWithToken:AJson[@"token"]  success:^(NSString *userId) {
//                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
//                MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
//                [[NSUserDefaults standardUserDefaults] setObject:userModel.phone forKey:kUserPhone];
//                [MBUserModel sharedMBUserModel].isLoginFlag = YES;
//                [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
//                NSLog(@"自动登录====================userInfo  %@",userModel.userInfo.headUrl);
//            } error:^(RCConnectErrorCode status) {
//                [MBProgressHUD showError:[NSString stringWithFormat:@"登陆的错误码为:%ld", (long)status]];
//            } tokenIncorrect:^{
//                //token过期或者不正确。
//                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
//                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
//                [MBProgressHUD showError:@"token错误"];
//            }];
//
//        } failure:^(id  _Nonnull AJson) {
//
//        }];
//    }
    return YES;
}

- (void)needLoginVC:(MBBaseController *)baseVC
{
    MBLoginController *loginVC = [[MBLoginController alloc]init];
    [baseVC presentViewController:loginVC animated:YES completion:nil];
}


/*登陆腾讯IM*/
-(void)tencentChatLoginWith:(MBUserModel *)model{
    TIMLoginParam * login_param = [[TIMLoginParam alloc ]init];
    // identifier 为用户名，userSig 为用户登录凭证
    // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
    login_param.identifier = [NSString stringWithFormat:@"%@",model.userInfo.userId];
    login_param.userSig = model.userSig;
    login_param.appidAt3rd = [NSString stringWithFormat:@"%i",TencentChatAppid];
    [[TIMManager sharedInstance] login: login_param succ:^(){
        NSLog(@"Login Succ");
    } fail:^(int code, NSString * err) {
        NSLog(@"Login Failed: %d->%@", code, err);
    }];
}

- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *userInfo))completion
{
    NSLog(@"getUserInfoWithUserId = %@",userId);
    if ([userId isEqualToString:[NSString stringWithFormat:@"%@",[MBUserModel sharedMBUserModel].userInfo.userId]]) {
        return completion([[RCUserInfo alloc] initWithUserId:userId name:[MBUserModel sharedMBUserModel].userInfo.nickname portrait:[MBUserModel sharedMBUserModel].userInfo.headUrl]);
    }else
    {
        NSDictionary *dict = @{
                               @"userId":[MBUserModel sharedMBUserModel].userInfo.userId,
                               @"beUserId":userId
                               };
        [MBHttpRequset requestWithUrl:kTradeid_userCenter_getPersonalData setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
            MBUserCenterModel *centerModel = [[MBUserCenterModel alloc]initWithDict:AJson];
            return completion([[RCUserInfo alloc] initWithUserId:[NSString stringWithFormat:@"%@",centerModel.userInfo.uId] name:centerModel.userInfo.nickname portrait:centerModel.userInfo.headUrl]);
        } failure:^(id  _Nonnull AJson) {
        }];

        
    }
    
}

//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//    
//    
//    return YES;
//}

//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
//{
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//    }
//    return YES;
//}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)configUMShare {
//    [[UMSocialManager defaultManager] setUmSocialAppkey:UMApppKey];
    [UMConfigure initWithAppkey:UMAppKey channel:@"Appstore"];
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMWeChatKey appSecret:UMWeChatSecret redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:UMQQAppID appSecret:UMQQKey redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:UMWeiboAppID appSecret:UMWeiboSecret redirectURL:@"http://mobile.umeng.com/social"];
}
/* IQKeyboardManager*/
-(void)configKeyboardManager
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
}

- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion {
}
    
-(void)configTXChat {
    TIMSdkConfig *sdkConfig = [[TIMSdkConfig alloc] init];
    sdkConfig.sdkAppId = TencentChatAppid;
    sdkConfig.accountType = TencentChatAccountType;
    sdkConfig.disableLogPrint = YES; // 是否允许log打印
    sdkConfig.logLevel = TIM_LOG_DEBUG; //Log输出级别（debug级别会很多）
//    sdkConfig.logPath =  logPath; //Log文件存放在哪里？
    [[TIMManager sharedInstance] initSdk:sdkConfig];
}

@end
